#include <gba.h>
#include "tetattds.h"

#include <stdio.h>

// #include "menubackground_bin.h"

// #include "splash2_bin.h"
// #include "splash2_map_bin.h"
// #include "splash2_pal_bin.h"

#include "fieldgraphics.h"
#include "util.h"
#include "settings.h"
#include "sramsettings.h"
#include "statusdialog.h"
#include "state.h"
#include "sprite.h"

#include "mappy.h"

#define BLEND_SRC_ALL 0x003F

static unsigned int currentTime = 0;

char name[10] = "GBA";
Settings* settings = NULL;

void SeedRandom()
{
	srand(currentTime);
}

void ShowSplashScreen()
{
// 	swiWaitForVBlank();
// 	lcdMainOnBottom();
	
// 	// main screen
// 	videoSetMode(
// 		MODE_0_2D |
// 		DISPLAY_BG0_ACTIVE);
// 	// 128K
// 	vramSetBankA(VRAM_A_MAIN_BG);

// 	// palette
// 	Decompress(BG_PALETTE, splash2_pal_bin);

// 	// splashscreen
// 	BG0_CR =
// 		BG_32x32 |
// 		BG_TILE_BASE(BACKGROUND_TILE_BASE) |
// 		BG_MAP_BASE(BACKGROUND_MAP_BASE) |
// 		BG_PRIORITY(BACKGROUND_PRIORITY) |
// 		BG_256_COLOR;
// 	Decompress((void*)BG_TILE_RAM(BACKGROUND_TILE_BASE), splash2_bin);
// 	Decompress((void*)BG_MAP_RAM(BACKGROUND_MAP_BASE), splash2_map_bin);
	
// 	// fade in
// 	for(int i = 31; i >= 0; i--)
// 	{
// 		BLEND_Y = i>>1;
// 		SUB_BLEND_Y = i>>1;
// 		swiWaitForVBlank();
// 	}
}
	
void HideSplashScreen()
{
// 	// fade out
// 	BLEND_CR = BLEND_FADE_BLACK | BLEND_SRC_ALL;
// 	SUB_BLEND_CR = BLEND_FADE_BLACK | BLEND_SRC_ALL;
	
// 	for(int i = 0; i < 32; i++)
// 	{
// 		BLEND_Y = i>>1;
// 		SUB_BLEND_Y = i>>1;
// 		swiWaitForVBlank();
// 	}
}

void InitSettings()
{		
	settings = new SramSettings();
	settings->Load();
}

// TODO: Move this someplace else
void InitGui();

int main(void)
{
	irqInit();
	irqEnable(IRQ_VBLANK); // needed by VBlankIntrWait()
	
	Sprite::InitSprites();
	g_fieldGraphics = new FieldGraphics();
	InitGui();
	InitStates();
	
	while(true)
	{
		StateTick();
		VBlankIntrWait();
	}

	return 0;
}

void* Decompress(const void* source, int* size)
{
	u32 header = *(u32*)source;
	ASSERT((header & 0xFF) == 0x10);

	int uncompressedSize = header >> 8;

	void* temp = malloc(uncompressedSize);

	LZ77UnCompWram((void*)source, temp);

	*size = uncompressedSize;
	return temp;
}

void Decompress(void* destination, const void* source)
{
	u32 header = *(u32*)source;
	ASSERT((header & 0xFF) == 0x10);

	int uncompressedSize = header >> 8;
	
	void* temp = malloc(uncompressedSize);

	LZ77UnCompWram((void*)source, temp);

	memcpy(destination, temp, uncompressedSize);
	free(temp);
}

